package com.geek.factory.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.geek.factory.entity.StockCheckDetail;
import com.geek.factory.entity.StockCheckTask;
import com.geek.factory.mapper.StockCheckTaskMapper;
import com.geek.factory.service.IStockCheckDetailService;
import com.geek.factory.service.IStockCheckTaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author author
 * @since 2025-06-29
 */
@Service
@Slf4j
public class StockCheckTaskServiceImpl extends ServiceImpl<StockCheckTaskMapper, StockCheckTask> implements IStockCheckTaskService {

    @Autowired
    private IStockCheckDetailService stockCheckDetailService;

    @Override
    @Transactional
    public boolean createTask(StockCheckTask task) {
        log.info("创建盘点任务: {}", task);

        // 设置默认值
        task.setCompletedItems(0);
        task.setStatus(StockCheckTask.STATUS_ASSIGNED); // 使用状态常量
        task.setCreatedTime(LocalDateTime.now());

        // 根据盘点单ID和区域计算分配物品数量
        if (task.getAssignedItems() == null) {
            QueryWrapper<StockCheckDetail> wrapper = new QueryWrapper<>();
            wrapper.eq("check_id", task.getCheckId());

            if (task.getAssignedArea() != null && !task.getAssignedArea().isEmpty()) {
                wrapper.eq("location", task.getAssignedArea());
            }

            // 将long类型转换为int类型
            int count = (int) stockCheckDetailService.count(wrapper);
            task.setAssignedItems(count);
        }

        return this.save(task);
    }

    @Override
    @Transactional
    public boolean updateTaskProgress(Integer taskId, Integer completedItems) {
        log.info("更新任务进度: taskId={}, completedItems={}", taskId, completedItems);

        StockCheckTask task = this.getById(taskId);
        if (task == null) {
            log.error("任务不存在: taskId={}", taskId);
            return false;
        }

        task.setCompletedItems(completedItems);

        // 如果完成数等于分配数，自动更新状态为已完成
        if (completedItems >= task.getAssignedItems()) {
            task.setStatus(StockCheckTask.STATUS_COMPLETED);
        } else if (completedItems > 0) {
            task.setStatus(StockCheckTask.STATUS_IN_PROGRESS);
        } else {
            task.setStatus(StockCheckTask.STATUS_ASSIGNED);
        }

        return this.updateById(task);
    }

    @Override
    @Transactional
    public boolean updateTaskStatus(Integer taskId, String status) {
        log.info("更新任务状态: taskId={}, status={}", taskId, status);

        StockCheckTask task = this.getById(taskId);
        if (task == null) {
            log.error("任务不存在: taskId={}", taskId);
            return false;
        }

        // 转换状态值
        String newStatus;
        switch (status.toLowerCase()) {
            case "待执行":
            case "待开始":
                newStatus = StockCheckTask.STATUS_ASSIGNED;
                break;
            case "进行中":
                newStatus = StockCheckTask.STATUS_IN_PROGRESS;
                break;
            case "已完成":
                newStatus = StockCheckTask.STATUS_COMPLETED;
                break;
            default:
                log.error("无效的状态值: {}", status);
                return false;
        }

        task.setStatus(newStatus);

        // 如果状态是已完成，确保完成数等于分配数
        if (StockCheckTask.STATUS_COMPLETED.equals(newStatus)) {
            task.setCompletedItems(task.getAssignedItems());
        }

        return this.updateById(task);
    }

    @Override
    public Map<String, Object> getTaskStats(Integer checkId) {
        log.info("获取盘点任务统计: checkId={}", checkId);

        Map<String, Object> stats = new HashMap<>();

        QueryWrapper<StockCheckTask> wrapper = new QueryWrapper<>();
        wrapper.eq("check_id", checkId);

        // 统计总数，将long转为int
        int totalTasks = (int) this.count(wrapper);

        // 统计各状态的任务数量，将long转为int
        QueryWrapper<StockCheckTask> pendingWrapper = new QueryWrapper<>();
        pendingWrapper.eq("check_id", checkId);
        pendingWrapper.eq("status", StockCheckTask.STATUS_ASSIGNED);
        int pendingTasks = (int) this.count(pendingWrapper);

        QueryWrapper<StockCheckTask> inProgressWrapper = new QueryWrapper<>();
        inProgressWrapper.eq("check_id", checkId);
        inProgressWrapper.eq("status", StockCheckTask.STATUS_IN_PROGRESS);
        int inProgressTasks = (int) this.count(inProgressWrapper);

        QueryWrapper<StockCheckTask> completedWrapper = new QueryWrapper<>();
        completedWrapper.eq("check_id", checkId);
        completedWrapper.eq("status", StockCheckTask.STATUS_COMPLETED);
        int completedTasks = (int) this.count(completedWrapper);

        stats.put("totalTasks", totalTasks);
        stats.put("pendingTasks", pendingTasks);
        stats.put("inProgressTasks", inProgressTasks);
        stats.put("completedTasks", completedTasks);
        stats.put("completionRate", totalTasks > 0 ? (double) completedTasks / totalTasks * 100 : 0);

        return stats;
    }
}